package com.wench.lock;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * list集合线程不安全
 * 异常演示     ConcurrentModificationException
 */
public class ThreadDemo4 {

    public static void main(String[] args) {

//        List<String> list = new ArrayList<>();

        //  Vector解决
//        List<String> list = new Vector<>();

        //  Collections解决
//        List<String> list = Collections.synchronizedList(new ArrayList<>());

        //  CopyOnWriteArrayList解决
//        List<String> list = new CopyOnWriteArrayList<>();
//
//        for (int i = 0; i < 30; i++) {
//            new Thread(() -> {
//                list.add(UUID.randomUUID().toString().substring(0, 4));
//
//                System.out.println(list);
//            }, String.valueOf(i)).start();
//        }

        //  HashSet演示
//        Set<String> set = new HashSet<>();

        // CopyOnWriteArraySet解决
//        Set<String> set = new CopyOnWriteArraySet<>();
//
//        for (int i = 0; i < 30; i++) {
//            new Thread(() -> {
//                set.add(UUID.randomUUID().toString().substring(0, 4));
//                System.out.println(set);
//            }, String.valueOf(i)).start();
//        }

        //  HashMap演示
//        Map<String,String> map = new HashMap<>();

        // ConcurrentHashMap解决
        Map<String,String> map = new ConcurrentHashMap<>();

        for (int i = 0; i < 30; i++) {
            String key = String.valueOf(i);
            new Thread(() -> {
                map.put(key,UUID.randomUUID().toString().substring(0, 4));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }
}
